/*
 * Copyright 2017 hv0912
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.vimhe.ezimp2.util;

import com.vimhe.ezimp2.config.exception.ConfigException;
import com.vimhe.ezimp2.exception.ImportException;

/**
 * 把Excel中的列索引字符串和对应的数字相互转换
 *
 * @author Vimhe
 */
public final class ExcelColumnIndexUtils {

    private ExcelColumnIndexUtils() {
    }

    /**
     * 把字母转换成数字
     * <pre>
     *     “A”  => “1”
     *     “C”  => “3”
     *     “AA” => “27”
     * </pre>
     *
     * @param name 列名称
     * @return 索引
     */
    public static int index2Number(String name) {
        if (StringUtils.isBlank(name)) {
            throw new ImportException("解析工作表失败，空的列索引");
        }

        name = name.toUpperCase();
        char[] chars = name.toCharArray();
        int n = 0;
        for (int i = chars.length - 1, j = 1; i >= 0; i--, j *= 26) {
            char c = chars[i];
            if (c < 'A' || c > 'Z') {
                throw new ConfigException("解析工作表失败，无效的列索引：" + c);
            }
            n += (c - 64) * j;
        }
        return n;
    }

    /**
     * 把数字转换成字母
     * <pre>
     *     “1”  => “A”
     *     “3”  => “C”
     *     “27” => “AA”
     * </pre>
     *
     * @param index 索引
     * @return 列名称
     */
    public static String number2Index(int index) {
        StringBuilder name = new StringBuilder();
        while (index > 0) {
            int m = index % 26;
            if (m == 0) {
                m = 26;
            }
            name.insert(0, (char) (m + 64));
            index = (index - m) / 26;
        }

        return name.toString();
    }

}
